package com.tancire.framework.web.service;

import com.tancire.common.constant.Constants;
import com.tancire.common.core.domain.entity.SysUser;
import com.tancire.common.core.domain.model.LoginUser;
import com.tancire.common.enums.UserSource;
import com.tancire.common.enums.UserStatus;
import com.tancire.common.exception.ServiceException;
import com.tancire.common.utils.ServletUtils;
import com.tancire.common.utils.StringUtils;
import com.tancire.net.domain.NetUser;
import com.tancire.net.service.ICrmCompanyService;
import com.tancire.net.service.INetUserService;
import com.tancire.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private ISysUserService userService;

    @Resource
    private SysPasswordService passwordService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private INetUserService netUserService;

    @Resource
    private ICrmCompanyService crmCompanyService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        int userSource = this.getCurrentUserSource();
        if (UserSource.SYSTEM.getCode() == userSource) {
            // 系统账户登录
            SysUser user = userService.selectUserByUserName(username);
            if (StringUtils.isNull(user)) {
                log.info("登录用户：{} 不存在.", username);
                throw new ServiceException("登录用户：" + username + " 不存在");
            } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                log.info("登录用户：{} 已被删除.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                log.info("登录用户：{} 已被停用.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已停用");
            }
            passwordService.validate(user);
            user.setUserSource(UserSource.SYSTEM.getCode());
            return createLoginUser(user);
        } else if (UserSource.MEMBER.getCode() == userSource) {
            // 微信小程序登录
            NetUser netUser = netUserService.selectNetUserByOpenId(username);
            if (StringUtils.isNull(netUser) &&  StringUtils.isBlank(netUser.getAccount())) {
                log.info("登录用户：{} 不存在.", username);
                throw new ServiceException("登录用户：" + username + " 不存在");
            }
            SysUser user = new SysUser();
            user.setUserId(netUser.getId());
            user.setNickName(netUser.getNickname());
            user.setUserName(username);
            user.setAvatar(netUser.getAvatar());
            user.setPhonenumber(netUser.getPhone());
            user.setAccount(netUser.getAccount());
            // user.setPassword(netUser.getPassword());
            Set<String> ps = new HashSet<>();
            ps.add("net:user:union");
            user.setUserSource(UserSource.MEMBER.getCode());
            return new LoginUser(netUser.getId(), 110L, user, ps);
        } else if (UserSource.COMPANY.getCode() == userSource) {
            // 企业账号登录
            SysUser user = crmCompanyService.selectCrmCompanyByAccount(username);
            if (StringUtils.isNull(user)) {
                log.info("登录用户：{} 不存在.", username);
                throw new ServiceException("登录用户：" + username + " 不存在");
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                log.info("登录用户：{} 已被停用.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已停用");
            }
            Set<String> prs = new HashSet<>();
            prs.add("company:user:union");
            return new LoginUser(user.getUserId(), 110L, user, prs);
        }
        return null;
    }

    /**
     * 获取当前请求头数据
     *
     * @return
     */
    private int getCurrentUserSource() {
        try {
            String us = ServletUtils.getRequest().getHeader(Constants.TANCIRE_SOURCE_KEY);
            return Integer.parseInt(us);
        } catch (Exception e) {
            throw new ServiceException("非法请求");
        }
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
